import AliyunOSSUpload from '@/components/AliyunOSSUpload';
import { department_select } from '@/services/department';
import { add_edit_platformuser, filedlist, platformuser_info } from '@/services/platformuser';
import { role_select } from '@/services/role';
import area from '@/utils/area';
import {
  ActionType,
  ProForm,
  ProFormDatePicker,
  ProFormGroup,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Cascader, Divider, Form, message, Modal, Spin, Switch, Transfer, TreeSelect } from 'antd';
import { useEffect, useState } from 'react';
interface Iprops {
  isShowEditModal: (show: boolean) => void;
  isEditModalOpen: boolean;
  id: number | undefined;
  actionRef: React.MutableRefObject<ActionType | undefined>;
}
type T = {
  disabled: boolean;
  status: number;
  value: any;
  id: any;
  title: any;
  name: any;
  pId: any;
  parent_id: any;
};
const EditStaff = (props: Iprops) => {
  const { isEditModalOpen, isShowEditModal, actionRef, id } = props;
  // 头像地址
  const [imageUrl, setImageUrl] = useState(undefined);
  // 存储科室列表
  const [departmentlist, setdepartmentlist] = useState();
  // 存储角色列表
  const [rolelist, setrolelist] = useState();
  // 穿梭框
  const [targetKeys, setTargetKeys] = useState<any>();
  const [selectedKeys, setSelectedKeys] = useState<any>([]);
  // 存储员工详情信息
  const [staffInfo, setStaffInfo] = useState<any>(undefined);
  // 地区
  const [areaname, setareaname] = useState<any>();
  // 组件初始化渲染，获取科室列表与角色列表以及员工详情
  useEffect(() => {
    // console.log('id', id);
    const getData = async () => {
      if (id) {
        let request_body = {
          id,
        };
        let res: any = await platformuser_info(request_body);
        // console.log('员工详情', res);
        if (res.msg == 'ok') {
          // 设置员工详情
          setStaffInfo(res.data);
          //处理头像
          setImageUrl(res.data.info.head_img);
          //处理角色
          if (res.data.role_ids) {
            let role_ids = res.data.role_ids?.split(',');
            let role_array = JSON.parse(role_ids).map((item: string | number) => {
              return +item;
            });
            // console.log(role_array);
            setTargetKeys(role_array);
          }
          //处理省市区名称
          setareaname([
            res.data.info.province_name,
            res.data.info.city_name,
            res.data.info.area_name,
          ]);
        }
      }
    };
    getData();
    get_select_department();
    get_roles();
  }, []);

  // 编辑员工
  const edit_staff = async (value: Record<string, any>) => {
    if ('status' in value) {
      var switch_status = value.status ? 1 : 0;
    } else {
      var switch_status = 1;
    }
    console.log('value', value);
    // return;
    let request_body = {
      //必填项
      ...value,
      id,
      status: switch_status,
      role_ids: JSON.stringify(targetKeys.map((item: string) => item + '')),
    };
    let res: any = await add_edit_platformuser(request_body);
    if (res.msg == 'ok') {
      actionRef.current?.reload();
      message.success('员工编辑成功');
      isShowEditModal(false);
      onReset();
    } else {
      message.error(res.msg);
    }
  };
  // 获取科室列表
  const get_select_department = async () => {
    let params = await department_select();
    params.data?.map((item: T) => {
      item.disabled = item.status == 0 ? true : false;
      item.value = item.id;
      item.title = item.name;
      item.pId = item.parent_id;
    });
    setdepartmentlist(params.data);
  };
  // 获取角色列表 穿梭框
  const get_roles = async () => {
    let params = await role_select();
    params.data.map((item: { key: string; id: string }) => {
      item.key = item.id;
    });
    setrolelist(params.data);
  };
  // 穿梭框相关方法
  const TransferonChange = (nextTargetKeys: any, direction: any, moveKeys: any) => {
    setTargetKeys(nextTargetKeys);
  };
  const TransferonSelectChange = (sourceSelectedKeys: any, targetSelectedKeys: any) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };
  // 获取职称列表 获取婚姻状况列表 获取学历列表 获取民族列表
  const get_system_field = async (key: any) => {
    let request_body = {
      type: key,
    };
    let params: any = await filedlist(request_body);
    let res: any = [];
    params.data.map((item: { value: any; key: any }) => {
      let temp: any = {};
      temp.label = item.value;
      temp.value = item.key;
      res.push(temp);
    });
    return res;
  };
  // 地区改变事件
  const area_onChange = (_: any, option: { name: string }[]) => {
    setareaname([option[0].name, option[1].name, option[2].name]);
  };
  // 重置表单
  const onReset = () => {
    //穿梭框
    setTargetKeys([]);
  };
  return (
    <Modal
      title="编辑员工"
      centered
      open={isEditModalOpen}
      onCancel={() => isShowEditModal(false)}
      width={1200}
      destroyOnClose={true}
      footer={null}
    >
      <Divider />
      {staffInfo === undefined ? (
        <div
          style={{
            margin: '20px 0',
            marginBottom: '20px',
            padding: '30px 50px',
            textAlign: 'center',
          }}
        >
          <Spin size="large" />
        </div>
      ) : (
        <>
          <ProForm
            onReset={() => onReset()}
            onFinish={(value) => edit_staff(value)}
            submitter={{
              searchConfig: {
                submitText: '提交',
                resetText: '重置',
              },
              resetButtonProps: {
                style: {
                  // 隐藏重置按钮
                  display: 'block',
                  position: 'absolute',
                  left: 'calc(50% - 107px)',
                },
              },
              submitButtonProps: {
                style: {
                  display: 'block',
                  position: 'absolute',
                  right: 'calc(50% - 107px)',
                },
              },
            }}
          >
            <div style={{ display: 'flex' }}>
              <div style={{ width: '70%', flex: '6' }}>
                <ProFormGroup>
                  <ProFormText
                    width={280}
                    name="username"
                    label="员工姓名"
                    disabled={true}
                    placeholder="请输入员工姓名"
                    rules={[
                      {
                        required: true,
                        message: '请输入员工姓名',
                        validateTrigger: 'onBlur',
                      },
                      { pattern: /(^\S)((.)*\S)?(\S*$)/, message: '不能输入空格' },
                    ]}
                    initialValue={staffInfo.info.username}
                  />
                  <ProFormSelect
                    width={280}
                    request={async () => [
                      { label: '未知', value: 0 },
                      { label: '男', value: 1 },
                      { label: '女', value: 2 },
                    ]}
                    name="sex"
                    label="性别"
                    disabled={true}
                    rules={[
                      {
                        required: true,
                        message: '请选择性别',
                      },
                    ]}
                    initialValue={staffInfo.info.sex}
                  />
                  <ProFormDatePicker
                    name="birth"
                    label="出生日期"
                    width={280}
                    disabled={true}
                    rules={[
                      {
                        required: true,
                        message: '请选择出生日期',
                      },
                    ]}
                    initialValue={staffInfo.info.birth}
                  />
                  <ProFormText
                    width={280}
                    name="phone"
                    label="手机号"
                    disabled={true}
                    placeholder="请输入员工手机号"
                    rules={[
                      {
                        required: true,
                        message: '请输入员工手机号',
                        validateTrigger: 'onBlur',
                      },
                      {
                        pattern: /^1\d{10}$/,
                        message: '请输入正确的手机号',
                        validateTrigger: 'onBlur',
                      },
                    ]}
                    initialValue={staffInfo.info.phone}
                  />
                  <Form.Item
                    name="department_id"
                    label="所属科室"
                    rules={[{ required: true, message: '请选择所属科室' }]}
                    initialValue={staffInfo.department_id}
                  >
                    <TreeSelect
                      treeDataSimpleMode
                      style={{ width: '280px' }}
                      treeData={departmentlist}
                      placeholder="请选择科室"
                      treeDefaultExpandAll
                    />
                  </Form.Item>
                  <ProFormSelect
                    width={280}
                    request={async () => get_system_field('doctor_positional')}
                    name="positional"
                    label="职称"
                    rules={[
                      {
                        required: true,
                        message: '请选择职称',
                      },
                    ]}
                    initialValue={staffInfo.positional}
                  />
                  <ProFormSelect
                    width={280}
                    request={async () => get_system_field('marital_status')}
                    name="marital_status"
                    disabled={true}
                    label="婚姻状况"
                    initialValue={staffInfo.info.marital_name}
                  />
                  <ProFormSelect
                    width={280}
                    request={async () => get_system_field('education')}
                    name="education"
                    disabled={true}
                    label="学历"
                    initialValue={staffInfo.info.education_name}
                  />
                  <ProFormSelect
                    width={280}
                    request={async () => get_system_field('nation_type')}
                    name="nation_type"
                    disabled={true}
                    label="民族"
                    initialValue={staffInfo.info.nation_type_name}
                  />
                  <Form.Item
                    name="area"
                    label="地址"
                    initialValue={
                      staffInfo.info.province_name
                        ? [
                            staffInfo.info.province_name,
                            staffInfo.info.city_name,
                            staffInfo.info.area_name,
                          ]
                        : ''
                    }
                  >
                    <Cascader
                      style={{ width: '280px' }}
                      options={area}
                      disabled={true}
                      onChange={area_onChange}
                      placeholder="请选择地区"
                      fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                    />
                  </Form.Item>
                  <ProFormText
                    width={280}
                    name="address"
                    label="详细地址"
                    disabled={true}
                    placeholder="请输入详细地址"
                    initialValue={staffInfo.info.address}
                  />
                </ProFormGroup>
              </div>
              <div style={{ width: '30%', flex: '1' }}>
                <ProForm.Item name="head_img" label="头像">
                  <div>
                    <AliyunOSSUpload
                      status={true}
                      imageUrl={imageUrl}
                      setImageUrl={setImageUrl}
                    ></AliyunOSSUpload>
                  </div>
                </ProForm.Item>
                <Form.Item
                  name="status"
                  label="状态"
                  valuePropName="checked"
                  initialValue={staffInfo.status == 1}
                >
                  <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked={true} />
                </Form.Item>
              </div>
            </div>
            <Form.Item name="role" label="设置角色">
              <Transfer
                dataSource={rolelist}
                titles={['角色列表', '已有角色']}
                targetKeys={targetKeys}
                selectedKeys={selectedKeys}
                onChange={TransferonChange}
                onSelectChange={TransferonSelectChange}
                render={(item) => item.rolename}
                listStyle={{
                  width: 520,
                  height: 300,
                }}
              />
            </Form.Item>
            <br />
          </ProForm>
        </>
      )}
      <br />
    </Modal>
  );
};
export default EditStaff;
